<template>
  <el-drawer
    :close-on-press-escape="false"
    v-model="visible"
    size="100%"
    title="详细信息"
    :with-header="false"
    @close="handleClose"
  >
    <div class="station-drawer">
      <div class="map-box">
        <StationMap ref="stationMapRef" @location="handleLocation" />
      </div>
      <div class="form-box">
        <div class="form-header">
          <h4>详细信息</h4>
          <div class="buttons" v-if="pageType == 'edit' || pageType == 'add'">
            <el-button plain @click="handleEdit(null)">取消</el-button>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </div>
          <div class="buttons" v-else-if="pageType == 'view'">
            <el-tooltip content="编辑" placement="top">
              <el-button
                v-if="auditType == 0"
                type="primary"
                icon="Edit"
                circle
                @click="handleEdit('edit')"
              />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-if="auditType == 0"
                type="danger"
                icon="Delete"
                circle
                @click="handleDelete"
              />
            </el-tooltip>
            <el-button plain @click="handleClose">关闭</el-button>
          </div>
        </div>
        <div style="flex: 1">
          <el-tabs type="card" style="height: 100%">
            <el-tab-pane label="站点信息" style="height: 100%">
              <el-form
                :model="formData"
                size="small"
                inline
                :disabled="pageType == 'view'"
              >
                <div class="station-info">
                  <!-- 第一段 -->
                  <div class="title">基础信息</div>
                  <div class="panel">
                    <div class="" style="width: 45%">
                      <div class="flex">
                        <el-input
                          v-model="formData.name"
                          placeholder="输入站点名称"
                          style="width: 100%"
                          size="small"
                          :class="{
                            hasUpdate: changedFields.includes('name'),
                          }"
                        ></el-input>
                      </div>
                      <!-- 图片 -->
                      <div class="carousel-box">
                        <el-upload
                          v-model:file-list="formData.photos"
                          class="avatar-uploader"
                          :action="`${baseUrl}/upload/index`"
                          :show-file-list="false"
                          multiple
                          :limit="10"
                          :on-success="handleAvatarSuccess"
                        >
                          <img
                            class="img"
                            src="@/assets/images/icon/upload.png"
                            alt=""
                          />
                        </el-upload>
                        <!-- 删除 -->
                        <el-carousel :interval="5000" arrow="always">
                          <el-carousel-item
                            height="200px"
                            v-for="item in formData.photos"
                            :key="item.uid"
                          >
                            <img style="width: 100%" :src="item.url" alt="" />
                            <el-button
                              class="delete-btn"
                              type="danger"
                              icon="Delete"
                              circle
                              @click="handleDeletePhoto(item)"
                            />
                          </el-carousel-item>
                        </el-carousel>
                      </div>
                    </div>
                    <div style="margin-left: 12px; flex: 1">
                      <el-form-item label="站点属性">
                        <el-select
                          v-model="formData.attribute"
                          placeholder="请选择"
                          :class="{
                            hasUpdate: changedFields.includes('attribute'),
                          }"
                        >
                          <el-option
                            v-for="item in attributeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="所属街道">
                        <el-select
                          v-model="formData.street_id"
                          placeholder="请选择"
                          :class="{
                            hasUpdate: changedFields.includes('street_id'),
                          }"
                          @change="handleStreetChange"
                        >
                          <el-option
                            v-for="item in streetOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="居委区域编号">
                        <el-select
                          v-model="formData.committee_id"
                          placeholder="请选择"
                          :class="{
                            hasUpdate: changedFields.includes('committee_id'),
                          }"
                        >
                          <el-option
                            v-for="item in committeeOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="分类">
                        <el-select
                          v-model="formData.category"
                          placeholder="请选择"
                          :class="{
                            hasUpdate: changedFields.includes('category'),
                          }"
                        >
                          <el-option label="中转站" value="中转站" />
                          <el-option label="集散场" value="集散场" />
                          <el-option
                            label="惠民回收服务点"
                            value="惠民回收服务点"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="名称">
                        <el-input
                          v-model="formData.name"
                          placeholder="请输入"
                          :class="{
                            hasUpdate: changedFields.includes('name'),
                          }"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="编码">
                        <el-input
                          v-model="formData.code"
                          placeholder="请输入"
                          :class="{
                            hasUpdate: changedFields.includes('code'),
                          }"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="地址">
                        <el-input
                          v-model="formData.address"
                          :class="{
                            hasUpdate: changedFields.includes('address'),
                          }"
                        >
                          <template #suffix>
                            <img
                              @click.stop="handleFindAddress"
                              style="width: 16px; cursor: pointer"
                              src="@/assets/images/icon/dingwei_icon.png"
                              alt=""
                            />
                          </template>
                        </el-input>
                      </el-form-item>
                      <el-form-item label="状态">
                        <el-select
                          v-model="formData.status"
                          placeholder="请选择"
                          :class="{
                            hasUpdate: changedFields.includes('status'),
                          }"
                        >
                          <el-option label="正常" value="正常" />
                          <el-option label="暂停使用" value="暂停使用" />
                          <el-option label="关闭" value="关闭" />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="面积(平方米)">
                        <el-input
                          v-model="formData.area"
                          placeholder="请输入"
                          :class="{
                            hasUpdate: changedFields.includes('area'),
                          }"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="服务街镇">
                        <el-select
                          v-model="formData.service_streets"
                          multiple
                          clearable
                          collapse-tags
                          collapse-tags-tooltip
                          placeholder="请选择"
                          :class="{
                            hasUpdate:
                              changedFields.includes('service_streets'),
                          }"
                        >
                          <el-option
                            v-for="item in streetOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          />
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>

                  <!-- 第二段 -->
                  <div class="title">运营信息</div>
                  <div class="panel" style="flex-direction: column">
                    <div class="box1">
                      <div class="box1-child-1">
                        <img
                          style="width: 350px"
                          src="@/assets/images/kehuishou/a.png"
                          alt=""
                        />

                        <el-select
                          v-model="formData.operator_company"
                          placeholder="请选择"
                          class="input1"
                          :class="{
                            'view-mode': pageType == 'view',
                            hasUpdate:
                              changedFields.includes('operator_company'),
                          }"
                        >
                          <el-option
                            v-for="item in operatorOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          />
                        </el-select>

                        <el-input
                          v-model="formData.contact_person"
                          :placeholder="
                            pageType == 'view' ? '' : '请输入联系人'
                          "
                          class="input1 input2"
                          :class="{
                            'view-mode': pageType == 'view',
                            hasUpdate: changedFields.includes('contact_person'),
                          }"
                        />
                        <el-input
                          v-model="formData.contact_phone"
                          class="input1 input3"
                          :class="{
                            'view-mode': pageType == 'view',
                            hasUpdate: changedFields.includes('contact_phone'),
                          }"
                          :placeholder="
                            pageType == 'view' ? '' : '请输入联系电话'
                          "
                        />
                        <el-input
                          v-model="formData.business_time"
                          class="input1 input4"
                          :class="{
                            'view-mode': pageType == 'view',
                            hasUpdate: changedFields.includes('business_time'),
                          }"
                          :placeholder="
                            pageType == 'view' ? '' : '请输入营业时间'
                          "
                        />
                      </div>
                      <div class="box1-child-2">
                        <el-form-item label="每周休息日">
                          <el-select
                            v-model="formData.weekly_rest_days"
                            placeholder="请选择"
                            multiple
                            collapse-tags
                            collapse-tags-tooltip
                            :class="{
                              hasUpdate:
                                changedFields.includes('weekly_rest_days'),
                            }"
                          >
                            <el-option label="周一" value="周一" />
                            <el-option label="周二" value="周二" />
                            <el-option label="周三" value="周三" />
                            <el-option label="周四" value="周四" />
                            <el-option label="周五" value="周五" />
                            <el-option label="周六" value="周六" />
                            <el-option label="周日" value="周日" />
                          </el-select>
                        </el-form-item>
                        <div class="box2">
                          <div class="title">其他1</div>
                          <el-input
                            v-model="formData.other1"
                            type="textarea"
                            :rows="3"
                            class="input5"
                            :placeholder="
                              pageType == 'view' ? '' : '请输入其他1'
                            "
                            :class="{
                              hasUpdate: changedFields.includes('other1'),
                            }"
                          />
                        </div>
                        <div class="box2">
                          <div class="title">其他2</div>
                          <el-input
                            v-model="formData.other2"
                            type="textarea"
                            :rows="3"
                            class="input5"
                            :placeholder="
                              pageType == 'view' ? '' : '请输入其他2'
                            "
                            :class="{
                              hasUpdate: changedFields.includes('other2'),
                            }"
                          />
                        </div>
                        <div class="box2">
                          <div class="title">备注</div>
                          <el-input
                            v-model="formData.remark"
                            type="textarea"
                            :rows="3"
                            class="input5"
                            :placeholder="
                              pageType == 'view' ? '' : '请输入备注'
                            "
                            :class="{
                              hasUpdate: changedFields.includes('remark'),
                            }"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <CustomDialog ref="customDialogRef" @confirm="handleDeleteConfirm" />
  </el-drawer>
</template>

<script setup>
import { ref, computed, onMounted, onActivated, watch, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import StationMap from "./stationMap.vue";
import CustomDialog from "@/components/customDialog.vue";
import {
  recyclableSitesAdd,
  recyclableSitesUpdate,
  recyclableSitesDelete,
} from "@/api/recyclable_sites";
import { streetsList, operatorsList, getCommittees } from "@/api/index";

defineOptions({
  name: "StationDrawer",
});
import { attributeOptions } from "../../options";
const baseUrl = ref(import.meta.env.VITE_BASE_URL);
const visible = ref(false); // 是否显示
const pageType = ref("view"); // 是否编辑 add edit view
const stationMapRef = ref(null); // 地图组件引用
const currentRow = ref(null); // 当前行
const customDialogRef = ref(null); // 自定义弹框引用
const streetOptions = ref([]); // 街道选项
const committeeOptions = ref([]); // 居委区域选项
const operatorOptions = ref([]); // 运营单位选项
const changedFields = ref([]); // 修改的字段
const openType = ref(null); // 打开弹框时的类型
const auditType = ref(0); // 是否审核 1 未审核 2 已审核 0其他
const emit = defineEmits(["refresh"]);
onMounted(() => {
  streetsList({}).then((res) => {
    if (res.code == 0) {
      streetOptions.value = res.data || [];
    }
  });
  operatorsList({ project_id: 4 }).then((res) => {
    if (res.code == 0) {
      operatorOptions.value = res.data || [];
    }
  });
});

// 每次组件激活时都会执行（如果使用了 Keep-Alive）
onActivated(() => {
  // 在这里添加你每次都需要执行的逻辑
  // 比如刷新数据、重置状态等
});

// 监听抽屉显示状态，每次打开时执行
watch(visible, (newVal) => {
  if (newVal) {
    // 在这里添加每次打开抽屉时都需要执行的逻辑
    // 比如刷新数据、重置状态等
  }
});
const formData = ref({
  id: null, // 主键ID
  street_id: null, // 所属街镇
  committee_id: null,
  category: null, // 分类
  name: null, // 名称
  code: null, // 编码
  address: null, // 地址
  longitude: null, // 经度
  latitude: null, // 纬度
  status: null, // 状态
  photos: [], // 照片 ['1','2']
  alias_name: null, // 站点名称
  area: null, // 面积
  operator_company: null, // 运营单位
  operator_id: null, // 运营单位ID
  service_streets: null, //服务街镇
  remark: null, //备注
  weekly_rest_days: [],
  other1: null,
  other2: null,
  operator_company_name: null,
  attribute: null,
});

const openDrawer = (row, type = "view", audit = 0) => {
  auditType.value = audit;
  pageType.value = type;
  console.log(type, "type");
  openType.value = type;
  currentRow.value = row;
  if (row) {
    // 如果formData.street_id，则获取居委区域
    if (row.street_id) {
      handleStreetChange(row.street_id);
    }
    formData.value = { ...row };
    if (typeof row.changed_fields === "object" && audit == 1) {
      changedFields.value = Object.keys(row.changed_fields);
    } else {
      changedFields.value = [];
    }
    console.log(changedFields.value, "变更的项-changedFields");
  } else {
    formData.value = {
      id: null, // 主键ID
      street_id: null, // 所属街镇
      committee_id: null,
      category: null, // 分类
      name: null, // 名称
      code: null, // 编码
      address: null, // 地址
      longitude: null, // 经度
      latitude: null, // 纬度
      status: null, // 状态
      photos: [], // 照片 ['1','2']
      alias_name: null, // 站点名称
      area: null, // 面积
      operator_company: null, // 运营单位
      operator_id: null, // 运营单位ID
      service_streets: null, //服务街镇
      remark: null, //备注
      weekly_rest_days: [],
      other1: null,
      other2: null,
      operator_company_name: null,
      attribute: null,
    };
    changedFields.value = [];
  }
  visible.value = true;

  // 打开抽屉后，初始化地图
  nextTick(() => {
    stationMapRef.value.initMap();
  });
};
const onSubmit = () => {
  let o = {
    ...formData.value,
  };
  let api = recyclableSitesAdd;
  if (currentRow.value?.id) {
    api = recyclableSitesUpdate;
    o.id = currentRow.value?.id;
  }
  api(o)
    .then((res) => {
      if (res.code == 0) {
        ElMessage.success("操作成功");
        handleClose();
        // 刷新列表
        emit("refresh");
      }
    })
    .catch(() => {
      ElMessage.error("操作失败");
    });
};
const handleClose = () => {
  visible.value = false;
};
// 编辑
const handleEdit = (type) => {
  console.log(type, "type");
  if (type) {
    pageType.value = type;
    return;
  }
  console.log(pageType.value, "type");
  if (pageType.value == "add") {
    handleClose();
    return;
  } else if (pageType.value == "edit") {
    if (openType.value == "edit") {
      handleClose();
      return;
    }
    pageType.value = "view";
  } else if (pageType.value == "view") {
    handleClose();
  }
};

// 上传图片
const handleAvatarSuccess = (res, file) => {
  console.log(res, file);
  file.url = res.data.url;
  if (res.code == 0) {
    // formData.value.photos.push(res.data.url);
  }
};

// 删除图片
const handleDeletePhoto = (item) => {
  formData.value.photos = formData.value.photos.filter((i) => i !== item);
};

// 删除
const handleDelete = () => {
  customDialogRef.value.openDialog("del");
  // ElMessageBox.confirm("确定删除吗？", "提示", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning",
  // }).then(() => {
  //   console.log("删除");
  // });
};

// 执行删除逻辑
const handleDeleteConfirm = () => {
  console.log("执行删除逻辑");
  recyclableSitesDelete({ id: currentRow.value.id }).then((res) => {
    if (res.code == 0) {
      ElMessage.success("删除成功");
      handleClose();
      // 刷新列表
      emit("refresh");
    }
  });
};

// 查找地址
const handleFindAddress = () => {
  let address = formData.value.address;
  if (!address) {
    ElMessage.error("请输入地址");
    return;
  }
  stationMapRef.value.setAddress(address);
};

// 处理位置
const handleLocation = (location) => {
  console.log(location, "location 厕所 子组件传过来的经纬度");
  formData.value.longitude = location.lng;
  formData.value.latitude = location.lat;
};

// 街道选择改变
const handleStreetChange = (value) => {
  console.log(value, "value");
  formData.value.committee_id = null;
  if (value) {
    committeeOptions.value = [];
    getCommittees({ street_id: value }).then((res) => {
      if (res.code == 0) {
        committeeOptions.value = res.data || [];
      }
    });
  }
};

defineExpose({
  openDrawer,
});
</script>

<style scoped lang="scss">
@use "./station.scss" as *;
@use "../../index.scss" as *;
</style>
